  //app.js
const request = require('./utils/request.js');
const validate = require('./utils/validate.js');
const common = require('./utils/common.js');
const pay = require('./utils/pay');
// const watch = require('./utils/watch');
const {
  M_ACCESS_TOKEN,
  M_CLIENT_SESSION_KEY,
  M_WX_CODE,
  M_USER_TYPE,
  M_SYS_UID,
  M_USERISAUTH
} = require('./constants/storage-key');
const {
  GET_TOKEN_URL,
  USER_INFO_URL,
  UPLOAD_URL,
  USER_SET_URL
} = require('./constants/config');

// 覆盖原生navigateBack, 当page数量为1时，点击返回按钮，跳转到主页-主要用于分享后的页面
const oldNavigateBack = wx.navigateBack;
Object.defineProperty(wx, 'navigateBack', {
  value: () => {
    const pages = getCurrentPages();
    console.log('pages', pages);
    if (pages.length > 1) {
      oldNavigateBack();
    } else {
      wx.switchTab({
        url: '/pages/index/index'
      });
    }
  },
  writable: true
});


App({
  onLaunch: function () {
    //隐藏系统tabbar
    //wx.hideTabBar();
    // 展示本地存储能力
    this._setSystemInfo();
    console.log("=========");
  },
  onLoad: function () {
    console.log("=====load====");
  },

  /**
   * 设置系统信息
   */
  _setSystemInfo() {
    try {
      if (!wx.getStorageSync('systeminfo')) {
        let res = wx.getSystemInfoSync();
        wx.setStorageSync('systeminfo', res);
      }
    } catch (err) {
      console.log(err);
    }

    // 设置自定义导航栏相关
    let menuButtonObject = wx.getMenuButtonBoundingClientRect()
    wx.getSystemInfo({
      success: res => {
        let statusBarHeight = res.statusBarHeight,
          navTop = menuButtonObject.top, //胶囊按钮与顶部的距离
          navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 3; //导航高度
        this.globalData.navHeight = navHeight
        this.globalData.navTop = navTop
        this.globalData.windowHeight = res.windowHeight
      },
      fail(err) {
        console.log(err)
      }
    })
  },
  /*
   * 初始化
   */
  // _startInit(para) {
  //   let m_fromshareuid = '';
  //   if (para.m_fromshareuid) {
  //     m_fromshareuid = para.m_fromshareuid;
  //   }


  //   return this._getAccessToken(m_fromshareuid).then(token => {
  //     //console.log(token)
  //     //console.log("------------")
  //     if (token == '') {
  //       return Promise.resolve('');
  //     }
  //     return this._getUserInfo().then(info => {
  //       return Promise.resolve('');
  //     });
  //   });
  //   // return this._getAccessToken()
  // },

  /**
   * 获取accesstoken
   */

  _getAccessToken(m_fromshareuid) {
    let _this = this;
    return new Promise((resolve, reject) => {
      //获取token
      let access_token = wx.getStorageSync(M_ACCESS_TOKEN);
      if (access_token) {
        return resolve(access_token);

      }
      wx.login({
        success: res => {
          console.log(res);
          wx.setStorageSync(M_WX_CODE, res.code);
          this.post(GET_TOKEN_URL, {
            code: res.code,
            m_fromshop: m_fromshareuid
          }).then(res => {
            console.log('login: get access_token', res);
            _this.globalData.uid = res.uid;
            wx.setStorageSync(M_SYS_UID, res.uid);
            wx.setStorageSync(M_CLIENT_SESSION_KEY, res.session_key);
            //wx.setStorageSync(M_OPEN_ID, res.openid);
            if (res.access_token) {
              wx.setStorageSync(M_ACCESS_TOKEN, res.access_token); //res.access_token  
              resolve(res.access_token);
            } else {
              // wx.setStorageSync(M_OPEN_ID, res.openid);
              resolve('');
            }
          });
        }
      });
    });
  },

  /**
   * 获取userinfo
   */
  _getUserInfo() {
    return this.get(USER_INFO_URL).then(data => {
      console.log('get user: ', data);
      //设置全局共用信息：userinfo
      wx.setStorageSync(M_USER_TYPE, data.usetype);
      this._setGlobalDataForUserInfo(data);

      return data;
    });

  },

  /**
   * 获取分享对象
   * @param {*} title 
   * @param {*} imageUrl 
   * @param {*} extra 
   */
  getShareObject(path, title, imageUrl) {
    //title
    let shareTitle = title;
    //path
    let sharePath = `pages/index/index?${path}&m_sysfrom=share`;
    let m_fromshareuid = this.globalData.userInfo ? this.globalData.userInfo.uid : '';
    sharePath = `${sharePath}&m_fromshareuid=${m_fromshareuid}`;
    //imageUrl
    console.log(sharePath);
    //let shareImage = '';
    //if (imageUrl == 1) {
     // shareImage = 'https://nventcn.infocode.cn/static/pic/2022-09-04/63140f4f08e9d858316397.jpg'
   // }
    //console.log("dddddd", shareImage)


    //返回分享对象
    //this.m_taskdone(3);
    return {
      title: shareTitle,
      path: sharePath,
      imageUrl: imageUrl,
      // success: function(res) {
      //     wx.showToast({
      //         title: '转发成功',
      //         icon: 'success',
      //         duration: 2000
      //     });
      // },
      // fail: function(res) {
      //     wx.showToast({
      //         title: '转发失败',
      //         icon: 'none'
      //     });
      // }
    };
  },
  /*
   * 分享回来入口解析
   */
  topageDone: function (topage, para) {
    //进入签到页  let path = 'topage=tgdetail&gid=' + this.data.currentGid;

    
    /*************new */
    if (topage == 'reportdetail') {
      let rid = para.rid
      let url_web = "/pages/report/report-detail?rid=" + rid//+ encodeURIComponent(url)
      this.m_tourl(url_web, '');
      return true;
    }
      if (topage == 'report') {
      let url = '/pages/report/report';
      this.m_tourl(url, '');
      return true;
    }
   
    
  
   
        

  },
  /**
   * 设置全局userinfo
   */
  _setGlobalDataForUserInfo(info) {
    let temp = {
      nickname: info.nickname || '',
      mobile: info.mobile || '',
      sex: info.sex || '',
      headimgurl: info.headimgurl || '',
      uid: info.uid || ''
    };

    this.globalData.userInfo = temp;
    //设置用户已经授权
    if (info.headimgurl != '') {
      this._checkUserAuthSet('y');
    }
  },
  //检查用户登录情况，如果没有授权则进入授权，否则进入手机登录
  checklogin(type) {
    if (type == 'mobile') {
      console.log("---mobile----")
      if (!this.globalData.userInfo.mobile || this.globalData.userInfo.mobile == '') {
        this.m_tourl("/pages/login/login");
        return false;
      }
      //进入手机号登录页
    } else {
      if (this.globalData.userInfo.headimgurl == "" && this.globalData.userInfo.nickname == '') {
        wx.getUserProfile({
          desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: (res) => {
            console.log(res.userInfo, '授权信息,进行存储')
            this._uploadUserInfo(res.userInfo);
          }
        })
        return false;
      }
    }
    return true;
  },
  /**
   * tabbar处理
   */
  editTabbar: function () {
    // let tabbar = this.globalData.tabBar;
    // let currentPages = getCurrentPages();
    // let _this = currentPages[currentPages.length - 1];
    // let pagePath = _this.route;
    // (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
    // for (let i in tabbar.list) {
    //     tabbar.list[i].selected = false;
    //     (tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);
    // }
    // _this.setData({
    //     tabbar: tabbar
    // });
  },
  onShow: function (e) {
    //隐藏系统tabbar
    //wx.hideTabBar();
    // this.getUnreadMsg()
    /*let that = this
    wx.onAppRoute(function (res) {
      let title = res.page.window.navigationBarTitleText;
      let path = res.path;
      let opentype = res.openType;
      let query = '';
      if (res.query) {
        query = JSON.stringify(res.query)
      }
      that.post('c=viewlog&a=add', {
        title: title,
        opentype: opentype,
        path: path,
        query: query
      }).then(res => {
        console.log("-----日志提交成功---")
      })
      console.log("--------", title, path, opentype, query)
    })*/
  },
  /*getUnreadMsg: function () {
    let timer = setInterval(() => {
      if (!this.globalData.isLock) {
        clearInterval(timer);
      }
      if (wx.getStorageSync(M_ACCESS_TOKEN) && this.globalData.isLock) {
        this.get('c=msg&a=unreadnum', {}).then(res => {
          console.log(res.unreadnum);
          //wx.setStorageSync(UN_READ_MSG, res.unreadnum);
          if (res.unreadnum > 0) {
            wx.setTabBarBadge({
              index: 4,
              text: '' + res.unreadnum + ''
            });
          } else {
            wx.removeTabBarBadge({
              index: 4
            });
          }
        });
      } else {
        clearInterval(timer);
      }
    }, 10000);
  },*/
  globalData: {
    userInfo: null,
    list: {},
    isLock: true,
    navHeight: 0,
    navTop: 0
  },
  get: request.get,
  post: request.post,
  pay: pay,
  validate: validate,
  // watch: watch.setWatcher,
  authInfo: {},
  m_showhint: common.m_showhint,
  m_showloading: common.m_showloading,
  m_hideloading: common.m_hideloading,
  m_tourl: common.m_tourl,
  m_showcheck: common.m_showcheck,
  formatRichText: common.formatRichText, //处理副文本编辑器中图片
  m_mobile: validate.mobile,
  m_email: validate.email,



    

  /****************************一下为通用函数 但是必须放在 app.js*******************************/
  //获取用户信息
  _uploadUserInfo(info) {
    // console.log('_uploadUserInfo');
    /**
     * 上传用户信息
     */
    this.post(USER_SET_URL, {
      nickname: info.nickName,
      sex: info.gender,
      headimgurl: info.avatarUrl,
      city: info.city,
      province: info.province
    }).then(data => {
      this._checkUserAuthSet('y');
      this._getUserInfo();
    }).catch(res => {

    });
  },
  /**
   * 通知
   */
  showNotify(title) {
    Notify({
      text: title || '当前网络不可用',
      duration: 3000,
      color: '#ffffff',
      backgroundColor: '#ff6055'
    });
  },
  //获取用户gps定位
  /*_getUserLocation(){
      wx.getLocation({
      success: res => {
        console.log("getLocation", res)
        this.setData({
          longitude: res.longitude,
          latitude: res.latitude
        })
      },
    })
  }*/
  _upload(filePath) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: UPLOAD_URL,
        filePath,
        header: {
          'content-type': 'multipart/form-data'
        },
        name: 'upload',
        formData: {
          'access_token': wx.getStorageSync('c=sys&a=uploadajax'),
          'type': 'common'
        },
        success(res) {
          resolve(JSON.parse(res.data));
        },
        fail(err) {
          reject(err);
        }
      });
    });
  },
  /************检查是否授权************** */
  _checkUserAuth: function () {
    let status = wx.getStorageSync(M_USERISAUTH);
    if (status == 'y') {
      return true;
    }
    return false;
  },
  _checkUserAuthSet: function (status) {
    //return '';
    console.log('-------status----------' + status);

    wx.setStorageSync(M_USERISAUTH, status);
  },
  /************task */
  m_taskdone: function (tid) {
    this.get('c=task&a=donetask', { tid: tid }).then(data => {
      if (data.scores > 0) {
        wx.showToast({
          title: '恭喜获得' + data.scores + '积分',
        })

      }
    }).catch(err => {
      /* console.log(err);
       wx.showToast({
           title: err.msg,
           icon: 'none'
       });*/
    })
  },
  _uploadUserInfoNewType(info) {
    // console.log('_uploadUserInfo');
    /**
     * 上传用户信息
     */
    this.post(USER_SET_URL, {
      nickname: info.nickname,
      sex: '',
      headimgurl: info.headimgurl,
      city: '',
      province: ''
    }).then(data => {
      this._checkUserAuthSet('y');
      this._getUserInfo();
    }).catch(res => {

    });
    return true;
  },

});